/*** function to create and then return a new Sprite object */
function Sprite(img_file, ancho, alto) {
	// var desfaseFrameRelativoPositivo = [3, 5, 0, 1, 2, 7];
	var desfaseFrameRelativo = [0, 2, -3, -2, -1, 4];
	this.incrementoFrame = 1;
	this.frame = 0;
	this.paso = 0;
	this.posX = 800;
	this.posY = 270;
	this.imagen = new Image();
	this.imagen.src = img_file;
	this.alto = alto;
	this.ancho = ancho;
	var that = this;
	this.incrementoFrame = 1;
	this.imagen.onload = function(){ 
		that.is_ready = true;
	}
	this.imagen.src = img_file;
	
	this.actualizarEstado = function(tiempoDelta) {
		// alert(this.posX);
		// alert(tiempoDelta);
		// alert(this.posX - 50 * tiempoDelta);
		this.posX = Math.floor(this.posX - 0.1 * tiempoDelta);
		if (this.paso == 0)
			this.posX = this.posX - desfaseFrameRelativo[this.frame];
		if (this.posX < 0)
			this.posX = 800;			
	}
	
	this.drawImage = function(contexto) {
		if(this.is_ready){
			contexto.clearRect(this.posX-15, this.posY, this.posX + 15 + this.ancho, this.alto);
			contexto.drawImage(this.imagen, this.frame * this.ancho, 0, this.ancho, this.alto, this.posX, this.posY, this.ancho, this.alto);
			this.paso = (this.paso + 1)% 3;
			if (this.paso == 0)
				this.frame = this.frame + this.incrementoFrame;
			if (this.frame > 4)
				this.incrementoFrame = -1;
			if (this.frame < 1)
				this.incrementoFrame = 1;
		}
	}	

}

function Principal(pcanvas) {
	this.canvas = pcanvas;
	this.contexto = pcanvas.getContext("2d");
	this.ancho = pcanvas.width;
	this.alto = pcanvas.height;
	this.sprite = new Sprite("imagenes/prota_paso_2.png", 64, 121);
	this.tiempoAnterior = new Date().getTime();
	
	this.actualizarJuego = function() {
		var tiempoActual = new Date().getTime();
		var tiempoDelta = tiempoActual - this.tiempoAnterior;
		this.tiempoAnterior = tiempoActual;
		this.sprite.actualizarEstado(tiempoDelta);
		//
		this.drawFrame();
	}
	
	this.drawFrame = function(){
		// El sprite se podria borrar a si mismo o solo borrar la zona por donde se va a mover y no todo
		//this.contexto.clearRect(0,0,this.ancho,this.alto);
		this.sprite.drawImage(this.contexto);
	}
}

window.onload = function() {
	var principal = new Principal(document.getElementById("canvasMov"));
	setInterval(function(){principal.actualizarJuego()}, 33);
}
